package com.nd.fastdp.security.resolver;

import com.nd.fastdp.framework.annotation.CurrentUser;
import com.nd.fastdp.framework.pojo.bo.LoginUser;
import com.nd.fastdp.security.cache.ShiroCache;
import com.nd.fastdp.security.util.JwtTokenUtil;
import com.nd.fastdp.security.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 当前用户MethodArgumentResolver
 */
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Lazy
    @Autowired
    private ShiroCache shiroCache;

    /**
     * 是否支持参数
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //判断方法参数是否带有@CurrentUser注解且参数类型为User或其子类
        return methodParameter.hasParameterAnnotation(CurrentUser.class) && LoginUser.class.isAssignableFrom(methodParameter.getParameterType());
    }

    /**
     * 解析变量
     */
    @SuppressWarnings("unchecked")
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取当前用户
        if(StringUtils.isNotEmpty(JwtTokenUtil.getToken())){
            String account = JwtUtil.getUsername(JwtTokenUtil.getToken());
            return  shiroCache.get(account);
        }
        return null;
    }

}